package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.Date;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultRowSorter;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.RowSorter;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import javax.swing.text.MaskFormatter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import net.sourceforge.jdatepicker.JDateComponentFactory;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import CommonGui.ColorRowRendererForTelOrder;
import CommonGui.MyComboBoxEditor;
import CommonGui.MyComboBoxRenderer;
import CommonGui.MyTableModelForTelOrdersJTable;
import DataObjects.ConstantObjects;
import Messages.MessageAddNewTelephoneOrder;
import Messages.MessageGetAllTelephoneOrdersForDate;
import Messages.MessageGetAllTelephoneOrdersForDateReply;
import Messages.MessageGetFiredRecipes;
import Messages.MessageGetFiredRecipesReply;
import Messages.MessageGetIdForNewTelephoneOrder;
import Messages.MessageGetIdForNewTelephoneOrderReply;
import Messages.MessageSavingReply;
import Messages.MessageUpdateTelephoneOrder;

import Messages.MessageUpdateTableOfTelephoneOrder;

public class PFTelephone_orders extends JPanel implements TableModelListener{
	  
	private MainMenu mainMenu;
	private Vector<Vector> allOrders;              //   time,name,numOfPersons,phoneNo,comments,status,restTable,telOrderId,date 
	
	private JComboBox statusCB;
	private VKTextField textField_id;
	private VKTextField nameTF;
	private VKTextField noOfPersonsTF;
	private VKTextField phoneNoTF;
	private VKTextField commentsTF;
	private VKTextField nameTxt;
	private VKFormattedTextField timeTF;
	private JDatePickerImpl newOrderDate;
	private JDatePickerImpl dateForSearch ;           //for searchUnits
	
	private JButton refreshBtn;	
	private JButton currentDateBtn;
	
	private JPanel checkOrderPanel;
	private JPanel insertOrderPanel ;
	private JPanel changeOrderPanel;
	private JPanel totalPanel;
	private JPanel searchAndTotalPanel;
	
	private RowSorter<DefaultTableModel> sorterStatus;
	private RowSorter<DefaultTableModel> sorterName;
	
	private MyTableModelForTelOrdersJTable dtm;
	private JTable tbl;
	private ConstantObjects constObj;
	
	private Vector<String> selectedRowVec=null;
	
	public static String tOrId;
	private String globalDate=null;
	
	
	
	public PFTelephone_orders(MainMenu mm, Vector<Vector> orders)
	{
		super();
		this.constObj=new ConstantObjects();
		this.setLayout(new BorderLayout());
		this.mainMenu=mm;
		this.allOrders=orders;
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		Date date = new Date();
		globalDate=dateFormat.format(date);
		initiliaze();
		Thread redLine =new Thread(new RedLine(this));
		redLine.setDaemon(true);
		redLine.start();
	}	
	
	private void initiliaze()
	{
		JScrollPane scrollPane = new JScrollPane(getTblOrders());
		this.add(scrollPane,BorderLayout.CENTER);
		this.add( getSearchAndTotalPanel(),BorderLayout.NORTH);
	}
	
	
	private JPanel getSearchAndTotalPanel()
	{
		searchAndTotalPanel=new JPanel();
		searchAndTotalPanel.setLayout(new BoxLayout(searchAndTotalPanel, BoxLayout.Y_AXIS));
		searchAndTotalPanel.add(getSearchUnits());
		searchAndTotalPanel.add(getTotalPanel());
		return searchAndTotalPanel;
	}
	
	private JPanel getTotalPanel()
	{
		totalPanel=new JPanel ();
		totalPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		refreshTotalPanel();
		return totalPanel;
	}
	
	
	private JPanel getInsertOrderPanel()
	{
		insertOrderPanel = new JPanel();
		insertOrderPanel.setBackground(new Color(255, 250, 205));
		insertOrderPanel.setLayout(new BoxLayout(insertOrderPanel, BoxLayout.Y_AXIS));
		insertOrderPanel.add( getInsertInfoPanel());
		insertOrderPanel.add( getCheckOrderPanel());
		insertOrderPanel.add(getButtonsPanel());
		return insertOrderPanel;
	}
	
	
	
	private JPanel getChangeOrderPanel()
	{
		changeOrderPanel = new JPanel();
		changeOrderPanel.setBackground(new Color(255, 250, 205));
		changeOrderPanel.setLayout(new BoxLayout(changeOrderPanel, BoxLayout.Y_AXIS));
		changeOrderPanel.add( getChangeInfoPanel());
		changeOrderPanel.add( getCheckOrderPanel());
		changeOrderPanel.add(getButtonsPanel2());
		return changeOrderPanel;
	}
	
	
//=========================================================================================================================================================	
	private JPanel getChangeInfoPanel()
	{
		JPanel changeInfoPanel=new JPanel();
		changeInfoPanel.setBackground(new Color(255, 250, 205));
		changeInfoPanel.setForeground(new Color(0, 0, 0));
		changeInfoPanel.setLayout(new SpringLayout());
		
		
		textField_id=new VKTextField(mainMenu);
		textField_id.setEditable(false);
		textField_id.setFont(new Font("Tahoma", Font.BOLD, 14));
		textField_id.setText(selectedRowVec.get(7));
	    JLabel idLbl = new JLabel("מספר הזמנה :", JLabel.TRAILING);
	    idLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
	    idLbl.setForeground(new Color(25, 25, 112));
	    idLbl.setLabelFor(textField_id);
	    changeInfoPanel.add(textField_id);
	    changeInfoPanel.add(idLbl);
		
		newOrderDate=getOrderDate();
		newOrderDate.setFont(new Font("Tahoma", Font.BOLD, 14));
		String fullDate=selectedRowVec.get(8);
		String year=fullDate.substring(0, 4);
		String month=fullDate.substring(5, 7);
		String day=fullDate.substring(8,10);
		newOrderDate.getModel().setDate(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day));
		JLabel dateLbl = new JLabel("תאריך ההזמנה :", JLabel.TRAILING);
		dateLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		dateLbl.setForeground(new Color(25, 25, 112));
		dateLbl.setLabelFor(newOrderDate);
		changeInfoPanel.add(newOrderDate);
		changeInfoPanel.add(dateLbl);
		
		
		
		 MaskFormatter mask = null;
	        try {
	            //
	            // Create a MaskFormatter for accepting phone number, the # symbol accept
	            // only a number. We can also set the empty value with a place holder
	            // character.
	            //
	            mask = new MaskFormatter("##:##");
	            mask.setPlaceholderCharacter('_');
	        } catch (ParseException e) {
	            e.printStackTrace();
	        }
	      
		       timeTF = new VKFormattedTextField(mainMenu,mask);
		       timeTF.setColumns(6);
		       timeTF.setText(selectedRowVec.get(0));
		       timeTF.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel timeLbl = new JLabel("שעת ההגעה :", JLabel.TRAILING);
		       timeLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       timeLbl.setForeground(new Color(25, 25, 112));
		       timeLbl.setLabelFor(timeTF);
		       changeInfoPanel.add(timeTF);
		       changeInfoPanel.add(timeLbl);
			
			
			   
			   nameTxt = new VKTextField(mainMenu);
			   nameTxt.setText(selectedRowVec.get(1));
			   nameTxt.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel nameLbl = new JLabel("שם המזמין :", JLabel.TRAILING);
		       nameLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       nameLbl.setForeground(new Color(25, 25, 112));
		       nameLbl.setLabelFor(nameTxt);
		       changeInfoPanel.add(nameTxt);
		       changeInfoPanel.add(nameLbl);
			   
			   
			   noOfPersonsTF = new VKTextField(mainMenu);
			   noOfPersonsTF.setFont(new Font("Tahoma", Font.BOLD, 14));
			   noOfPersonsTF.setText(selectedRowVec.get(2));
		       JLabel noOfPersonsLbl = new JLabel("מספר סועדים :", JLabel.TRAILING);
		       noOfPersonsLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       noOfPersonsLbl.setForeground(new Color(25, 25, 112));
		       noOfPersonsLbl.setLabelFor(noOfPersonsTF);
		       changeInfoPanel.add(noOfPersonsTF);
		       changeInfoPanel.add(noOfPersonsLbl);
			   
			   
			   phoneNoTF = new VKTextField(mainMenu);
			   phoneNoTF.setFont(new Font("Tahoma", Font.BOLD, 14));
			   phoneNoTF.setText(selectedRowVec.get(3));
		       JLabel phoneNoLbl = new JLabel("מספר טלפון :", JLabel.TRAILING);
		       phoneNoLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       phoneNoLbl.setForeground(new Color(25, 25, 112));
		       phoneNoLbl.setLabelFor(phoneNoTF);
		       changeInfoPanel.add(phoneNoTF);
		       changeInfoPanel.add(phoneNoLbl);
			   
			   
			   commentsTF = new VKTextField(mainMenu);
			   commentsTF.setFont(new Font("Tahoma", Font.BOLD, 12));
			   commentsTF.setText(selectedRowVec.get(4));
		       JLabel commentsLbl = new JLabel("הערות מאוחדות :", JLabel.TRAILING);
		       commentsLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       commentsLbl.setForeground(new Color(25, 25, 112));
		       commentsLbl.setLabelFor(commentsTF);
		       changeInfoPanel.add(commentsTF);
		       changeInfoPanel.add(commentsLbl);
			   			
			SpringUtilities.makeCompactGrid(changeInfoPanel,7, 2, //rows, cols
				     20, 20, //initX, initY
				       20, 20); //xPad, yPad
			
			
			
			
		return changeInfoPanel;
		
		
	}
	
	
	
	
	
	
	
	
	
	
	private JPanel getCheckOrderPanel()
	{
		checkOrderPanel=new JPanel();
		checkOrderPanel.setLayout(new BoxLayout(checkOrderPanel, BoxLayout.Y_AXIS));
		checkOrderPanel.setAlignmentX(CENTER_ALIGNMENT);
		return checkOrderPanel;
	}
	
	
	private JPanel getButtonsPanel()
	{
		JPanel buttonsPanel=new JPanel();
		buttonsPanel.setBackground(new Color(255, 250, 205));
		buttonsPanel.setForeground(new Color(0, 0, 0));
		buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
		buttonsPanel.add(getBtnSave());
		buttonsPanel.add(Box.createHorizontalStrut(10));
		buttonsPanel.add(getBtnNewOrder());
		buttonsPanel.add(Box.createHorizontalStrut(10));
		buttonsPanel.add(getBtnCancel());
		buttonsPanel.setPreferredSize(new Dimension(500,500));
		return buttonsPanel;
	}
	
	
	
	
	
	private JPanel getButtonsPanel2()
	{
		JPanel buttonsPanel=new JPanel();
		buttonsPanel.setBackground(new Color(255, 250, 205));
		buttonsPanel.setForeground(new Color(0, 0, 0));
		buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
		buttonsPanel.add(getBtnSave2());
		buttonsPanel.add(Box.createHorizontalStrut(10));
		buttonsPanel.add(getBtnNewOrder());
		buttonsPanel.add(Box.createHorizontalStrut(10));
		buttonsPanel.add(getBtnCancel());
		buttonsPanel.setPreferredSize(new Dimension(500,500));
		return buttonsPanel;
	}
	
	
	
	
	
	private JButton getBtnSave()
	{
		JButton btnSave=new JButton("שמור הזמנה");
		btnSave.setFont(new Font("Tahoma", Font.BOLD, 14));
		
		
		btnSave.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				JButton savebutt=(JButton) e.getSource();			
				checkOrderPanel.removeAll();
				Vector<String> checkingResult=inputCheck();
				int size=checkingResult.size();                          
				if(size==0)
				{
					JLabel goodLbl=new JLabel("כל הנתונים תקינים");
					goodLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
					goodLbl.setForeground(Color.blue);
					checkOrderPanel.add(goodLbl);
					
					Vector<String> order =new Vector<String>();
					
					int year=newOrderDate.getModel().getYear();
					int month=newOrderDate.getModel().getMonth()+1;
					int day=newOrderDate.getModel().getDay();
					
					order.add(textField_id.getText());
					order.add(Integer.toString(year)+"-"+Integer.toString(month)+"-"+Integer.toString(day));
					order.add(timeTF.getText());
					order.add(nameTxt.getText());
					order.add(noOfPersonsTF.getText());
					order.add(phoneNoTF.getText());
					order.add(commentsTF.getText());
					
					  
					 MessageAddNewTelephoneOrder msgNewOrder= new MessageAddNewTelephoneOrder(order);
					 
					 try {
							mainMenu.ms.client.sendToServer(msgNewOrder);
							MessageSavingReply result=(MessageSavingReply)mainMenu.ms.client.GetMessage();
							
							if (result.getResult()==1) 
							{
							JLabel goodLbl2=new JLabel("ההזמנה נשמרה בהצלחה");
							goodLbl2.setFont(new Font("Tahoma", Font.BOLD, 11));
							goodLbl2.setForeground(Color.blue);
							checkOrderPanel.add(goodLbl2);
							
							DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
							Date date = new Date();
							MessageGetAllTelephoneOrdersForDate msgAllOrders=new MessageGetAllTelephoneOrdersForDate(dateFormat.format(date));
							mainMenu.ms.client.sendToServer(msgAllOrders);
							MessageGetAllTelephoneOrdersForDateReply resultOrders=(MessageGetAllTelephoneOrdersForDateReply)mainMenu.ms.client.GetMessage();
							Vector<Vector> orders=resultOrders.getResult();
							allOrders.removeAllElements();
							for(int i=0 ; i<orders.size();i++)
							{
								allOrders.add(orders.get(i));
							}
							tbl.repaint();
							tbl.validate();
							mainMenu.getContentPane().validate();
							savebutt.setEnabled(false);
							
							}
							else
							{
								JLabel wrongLbl2=new JLabel("בעיית תקשורת . הנתונים לא נשמרו");
								wrongLbl2.setFont(new Font("Tahoma", Font.BOLD, 15));
								wrongLbl2.setForeground(Color.red);
								checkOrderPanel.add(wrongLbl2);
							}
							
							
							
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					 
					 
						
				}
				
				
				else  //wrong input-print all errors on check_panel
				{
					JLabel wrongLbl=new JLabel("הנתונים אינם תקינים :");
					wrongLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
					wrongLbl.setForeground(Color.red);
					checkOrderPanel.add(wrongLbl);
					for(int i=0;i<size;i++)
					{
						JLabel error=new JLabel(checkingResult.get(i));
						error.setForeground(Color.red);
						checkOrderPanel.add(error);
					}
				}
				
				
				
				mainMenu.getContentPane().validate();
				
		
			}
		});
		
		return btnSave;
	}
	
	
	
	
	
	private JButton getBtnSave2()
	{
		JButton btnSave=new JButton("שמור הזמנה");
		btnSave.setFont(new Font("Tahoma", Font.BOLD, 14));
		
		
		btnSave.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				JButton savebutt=(JButton) e.getSource();			
				checkOrderPanel.removeAll();
				Vector<String> checkingResult=inputCheck();
				int size=checkingResult.size();                          
				if(size==0)
				{
					JLabel goodLbl=new JLabel("כל הנתונים תקינים");
					goodLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
					goodLbl.setForeground(Color.blue);
					checkOrderPanel.add(goodLbl);
					
					Vector<String> order =new Vector<String>();
					
					int year=newOrderDate.getModel().getYear();
					int month=newOrderDate.getModel().getMonth()+1;
					int day=newOrderDate.getModel().getDay();
					
					order.add(textField_id.getText());
					order.add(Integer.toString(year)+"-"+Integer.toString(month)+"-"+Integer.toString(day));
					order.add(timeTF.getText());
					order.add(nameTxt.getText());
					order.add(noOfPersonsTF.getText());
					order.add(phoneNoTF.getText());
					order.add(commentsTF.getText());
					
					  
					 MessageUpdateTelephoneOrder msgUpdOrder= new MessageUpdateTelephoneOrder(order);
					 
					 try {
							mainMenu.ms.client.sendToServer(msgUpdOrder);
							MessageSavingReply result=(MessageSavingReply)mainMenu.ms.client.GetMessage();
							
							if (result.getResult()==1) 
							{
							JLabel goodLbl2=new JLabel("ההזמנה עודכנה בהצלחה");
							goodLbl2.setFont(new Font("Tahoma", Font.BOLD, 11));
							goodLbl2.setForeground(Color.blue);
							checkOrderPanel.add(goodLbl2);
							
							DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
							Date date = new Date();
							MessageGetAllTelephoneOrdersForDate msgAllOrders=new MessageGetAllTelephoneOrdersForDate(dateFormat.format(date));
							mainMenu.ms.client.sendToServer(msgAllOrders);
							MessageGetAllTelephoneOrdersForDateReply resultOrders=(MessageGetAllTelephoneOrdersForDateReply)mainMenu.ms.client.GetMessage();
							Vector<Vector> orders=resultOrders.getResult();
							allOrders.removeAllElements();
							for(int i=0 ; i<orders.size();i++)
							{
								allOrders.add(orders.get(i));
							}
							tbl.repaint();
							tbl.validate();
							mainMenu.getContentPane().validate();
							
							}
							else
							{
								JLabel wrongLbl2=new JLabel("בעיית תקשורת . הנתונים לא נשמרו");
								wrongLbl2.setFont(new Font("Tahoma", Font.BOLD, 15));
								wrongLbl2.setForeground(Color.red);
								checkOrderPanel.add(wrongLbl2);
							}
							
							
							
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					 
					 
						
				}
				
				
				else  //wrong input-print all errors on check_panel
				{
					JLabel wrongLbl=new JLabel("הנתונים אינם תקינים :");
					wrongLbl.setFont(new Font("Tahoma", Font.BOLD, 13));
					wrongLbl.setForeground(Color.red);
					checkOrderPanel.add(wrongLbl);
					for(int i=0;i<size;i++)
					{
						JLabel error=new JLabel(checkingResult.get(i));
						error.setForeground(Color.red);
						checkOrderPanel.add(error);
					}
				}
				
				
				
				mainMenu.getContentPane().validate();
				
		
			}
		});
		
		return btnSave;
	}
	
	
	
	
	
	private JButton getBtnCancel()
	{
		
		JButton btnCancel=new JButton("ביטול");
		btnCancel.setFont(new Font("Tahoma", Font.BOLD, 14));
		btnCancel.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{		
				((JButton)e.getSource()).getParent().getParent().getParent().remove(((JButton)e.getSource()).getParent().getParent());
				mainMenu.getContentPane().validate();
			}
		});
		return btnCancel;
	}
	
	
	
	
	private JButton getBtnNewOrder()
	{
		
		JButton btnNewOrder=new JButton("הזמנה חדשה");
		btnNewOrder.setFont(new Font("Tahoma", Font.BOLD, 14));
		btnNewOrder.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				addInsertOrderPanel();			
				
			}
		});
		return btnNewOrder;
	}
	
	
	private JPanel getInsertInfoPanel()
	{
		JPanel insertOrderPanel=new JPanel();
		insertOrderPanel.setBackground(new Color(255, 250, 205));
		insertOrderPanel.setForeground(new Color(0, 0, 0));
		insertOrderPanel.setLayout(new SpringLayout());
		
		MessageGetIdForNewTelephoneOrder msgGetId=new MessageGetIdForNewTelephoneOrder( );
		textField_id=new VKTextField(mainMenu);
		textField_id.setEditable(false);
		
		try {
			mainMenu.ms.client.sendToServer(msgGetId);
			MessageGetIdForNewTelephoneOrderReply resultID=(MessageGetIdForNewTelephoneOrderReply)mainMenu.ms.client.GetMessage();
			String orderId=resultID.getResultID();
			int newId=Integer.parseInt(orderId)+1;			
			textField_id.setText(Integer.toString(newId));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		textField_id.setFont(new Font("Tahoma", Font.BOLD, 14));
	    JLabel idLbl = new JLabel("מספר הזמנה :", JLabel.TRAILING);
	    idLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
	    idLbl.setForeground(new Color(25, 25, 112));
	    idLbl.setLabelFor(textField_id);
		insertOrderPanel.add(textField_id);
		insertOrderPanel.add(idLbl);
		
		newOrderDate=getOrderDate();
		newOrderDate.setFont(new Font("Tahoma", Font.BOLD, 14));
		JLabel dateLbl = new JLabel("תאריך ההזמנה :", JLabel.TRAILING);
		dateLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		dateLbl.setForeground(new Color(25, 25, 112));
		dateLbl.setLabelFor(newOrderDate);
		insertOrderPanel.add(newOrderDate);
		insertOrderPanel.add(dateLbl);
		
		
		
		 MaskFormatter mask = null;
	        try {
	            //
	            // Create a MaskFormatter for accepting phone number, the # symbol accept
	            // only a number. We can also set the empty value with a place holder
	            // character.
	            //
	            mask = new MaskFormatter("##:##");
	            mask.setPlaceholderCharacter('_');
	        } catch (ParseException e) {
	            e.printStackTrace();
	        }
	      
		       timeTF = new VKFormattedTextField(mainMenu,mask);
		       timeTF.setColumns(6);
		       timeTF.setText("0000");
		       timeTF.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel timeLbl = new JLabel("שעת ההגעה :", JLabel.TRAILING);
		       timeLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       timeLbl.setForeground(new Color(25, 25, 112));
		       timeLbl.setLabelFor(timeTF);
			   insertOrderPanel.add(timeTF);
			   insertOrderPanel.add(timeLbl);
			
			
			   
			   nameTxt = new VKTextField(mainMenu);
			   nameTxt.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel nameLbl = new JLabel("שם המזמין :", JLabel.TRAILING);
		       nameLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       nameLbl.setForeground(new Color(25, 25, 112));
		       nameLbl.setLabelFor(nameTxt);
			   insertOrderPanel.add(nameTxt);
			   insertOrderPanel.add(nameLbl);
			   
			   
			   noOfPersonsTF = new VKTextField(mainMenu);
			   noOfPersonsTF.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel noOfPersonsLbl = new JLabel("מספר סועדים :", JLabel.TRAILING);
		       noOfPersonsLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       noOfPersonsLbl.setForeground(new Color(25, 25, 112));
		       noOfPersonsLbl.setLabelFor(noOfPersonsTF);
			   insertOrderPanel.add(noOfPersonsTF);
			   insertOrderPanel.add(noOfPersonsLbl);
			   
			   
			   phoneNoTF = new VKTextField(mainMenu);
			   phoneNoTF.setFont(new Font("Tahoma", Font.BOLD, 14));
		       JLabel phoneNoLbl = new JLabel("מספר טלפון :", JLabel.TRAILING);
		       phoneNoLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       phoneNoLbl.setForeground(new Color(25, 25, 112));
		       phoneNoLbl.setLabelFor(phoneNoTF);
			   insertOrderPanel.add(phoneNoTF);
			   insertOrderPanel.add(phoneNoLbl);
			   
			   
			   commentsTF = new VKTextField(mainMenu);
			   commentsTF.setFont(new Font("Tahoma", Font.BOLD, 12));
		       JLabel commentsLbl = new JLabel("הערות מאוחדות :", JLabel.TRAILING);
		       commentsLbl.setFont(new Font("Tahoma", Font.BOLD, 12));
		       commentsLbl.setForeground(new Color(25, 25, 112));
		       commentsLbl.setLabelFor(commentsTF);
			   insertOrderPanel.add(commentsTF);
			   insertOrderPanel.add(commentsLbl);
			   			
			SpringUtilities.makeCompactGrid(insertOrderPanel,7, 2, //rows, cols
				     20, 20, //initX, initY
				       20, 20); //xPad, yPad
			
			
			
			
		return insertOrderPanel;
		
		
	}
	
	private JTable getTblOrders()
	{
		Vector <String> tblheader=new Vector<String>();
		
		
		tblheader.add("שעת ההגעה");
		tblheader.add("שם");
		tblheader.add("מספר סועדים");
		tblheader.add("מספר טלפון");
		tblheader.add("הערות");
		tblheader.add("סטטוס");
		tblheader.add("מספר שולחן");
		tblheader.add("1");
		tblheader.add("2");
		
		
		
		
		
		dtm=new MyTableModelForTelOrdersJTable(allOrders,tblheader);	 		
		tbl = new JTable(dtm);
		
        TableColumn tm = tbl.getColumnModel().getColumn(0);
        tbl.setDefaultRenderer(Object.class, new ColorRowRendererForTelOrder());
        					
		tbl.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		tbl.setFont(new Font("David", Font.BOLD, 16));
		tbl.removeColumn(tbl.getColumnModel().getColumn(8));
		tbl.removeColumn(tbl.getColumnModel().getColumn(7));
		tbl.getTableHeader().setFont( new Font( "Arial" , Font.BOLD, 17 ));
		tbl.getTableHeader().setBackground(new Color(173,216,230));
		tbl.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); 
	    tbl.setRowHeight(30);
		tbl.setFillsViewportHeight(true);
        tbl.setGridColor(new Color(25, 25, 112));
        tbl.setBackground(new Color(250, 235, 215));
        tbl.setForeground(new Color(0, 0, 0));
        tbl.setAutoCreateRowSorter(true);
        tbl.getModel().addTableModelListener(this);
        
        TableColumn col_6 = tbl.getColumnModel().getColumn(6);
        col_6.setCellRenderer(new MyComboBoxRenderer(constObj.getTableNo())); 
        col_6.setCellEditor(new MyComboBoxEditor(constObj.getTableNo()));
        TableColumn col_5 = tbl.getColumnModel().getColumn(5);
        col_5.setCellRenderer(new MyComboBoxRenderer(constObj.getOrderStatusForTable()));
       col_5.setCellEditor(new MyComboBoxEditor(constObj.getOrderStatusForTable()));        
        
        
        tbl.addMouseListener(new MouseAdapter() {
			   public void mouseClicked(MouseEvent e) {
			     if (e.getClickCount() == 1) {
			       JTable target = (JTable)e.getSource();
			       int row = target.getSelectedRow();
			       int column = target.getSelectedColumn();

			       if(row!=-1)
			       {
				       selectedRowVec=(Vector<String>) dtm.getDataVector().get(row);
			       }
			     }
			     
			     if (e.getClickCount() == 2){
			    	addChangeOrderPanel();
			         }
			     
			   }
			   
			 });
        
        
        return tbl;
	}
	
	
	
	private JPanel getSearchUnits()
	{
		JPanel searchUnits=new JPanel ();
		searchUnits.setBackground(new Color(255, 245, 238));
		searchUnits.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		searchUnits.add(getStatusCB());
		searchUnits.add(getStatusLbl());
		searchUnits.add(getNameTF());
		searchUnits.add(getNameLbl());
		dateForSearch=getOrderDate();
		searchUnits.add(dateForSearch);
		searchUnits.add(getRefreshBtn());
		searchUnits.add(getCurrentDateBtn());
		return searchUnits;
	}
	
	private JComboBox getStatusCB()
	{
		statusCB=new JComboBox(constObj.getOrderStatusForSearch());
		statusCB.addActionListener(new java.awt.event.ActionListener() 
	  	{
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				JComboBox statusBox = (JComboBox)e.getSource();
			    String selectedStatus = (String)statusBox.getSelectedItem(); 
			    filterByStatus(selectedStatus);
				} 
		});	
		return statusCB;
	}
	
	private void filterByStatus(String selStatus)
	{
		if(selStatus.equals("הכל"))
		{
			((DefaultRowSorter<DefaultTableModel, Integer>) sorterStatus).setRowFilter(null);
		}
		
		else 
		{
		sorterStatus = new TableRowSorter<DefaultTableModel>(dtm);     		   
	    tbl.setRowSorter(sorterStatus);  	    
	    RowFilter< DefaultTableModel  , Object> rf = null;   
	    //declare a row filter for your table model  
	    try  
	    {  
	        rf = RowFilter.regexFilter("^" + selStatus, 5);    
	        //initialize with a regular expression  
	    }  
	   catch (java.util.regex.PatternSyntaxException e1)  
	    {  
	        return;  
	    }  
	   
	    ((DefaultRowSorter<DefaultTableModel, Integer>) sorterStatus).setRowFilter(rf);
		}   //else
	}
	
	
	private VKTextField getNameTF()
	{
		nameTF=new VKTextField(mainMenu);
		nameTF.setColumns(15);
	
		KeyListener keyListener = new KeyListener() 
		{		      
			public void keyPressed(KeyEvent arg0) {}

			public void keyReleased(KeyEvent arg0) 
			{
				VKTextField nameField = (VKTextField)arg0.getSource();
				String selectedName = (String)nameField.getText();
				filterByName(selectedName);				
			}

			public void keyTyped(KeyEvent arg0) {}		
		};
		
		nameTF.addKeyListener(keyListener);		
		return nameTF;
	}
	
	private void filterByName(String name)
	{
		
		sorterName = new TableRowSorter<DefaultTableModel>(dtm);     		   
	    tbl.setRowSorter(sorterName);  	    
	    RowFilter< DefaultTableModel  , Object> rf = null;   
	    //declare a row filter for your table model  
	    try  
	    {  
	        rf = RowFilter.regexFilter(name, 1);    
	        //initialize with a regular expression  
	    }  
	   catch (java.util.regex.PatternSyntaxException e1)  
	    {  
	        return;  
	    }  
	   
	    ((DefaultRowSorter<DefaultTableModel, Integer>) sorterName).setRowFilter(rf);		
	}
	
	
	
	
	
	
	private JLabel getNameLbl()
	{
		JLabel nameLbl=new JLabel("   שם  :  ");
		nameLbl.setFont(new Font("Tahoma", Font.PLAIN, 13));
		return nameLbl;
	}
	
	
	
	private JLabel getStatusLbl()
	{
		JLabel roleLbl=new JLabel("   מצב  :  ");
		roleLbl.setFont(new Font("Tahoma", Font.PLAIN, 13));
		return roleLbl;
	}
	
	
	private JButton getRefreshBtn()
	{
		refreshBtn=new JButton("שינוי תאריך");
		
		refreshBtn.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {									
			
				int year=dateForSearch.getModel().getYear();
				int month=dateForSearch.getModel().getMonth()+1;
				int day=dateForSearch.getModel().getDay();
				globalDate=(Integer.toString(year)+"-"+Integer.toString(month)+"-"+Integer.toString(day));				
				MessageGetAllTelephoneOrdersForDate msgAllOrders=new MessageGetAllTelephoneOrdersForDate(globalDate);
				try {
					mainMenu.ms.client.sendToServer(msgAllOrders);
					MessageGetAllTelephoneOrdersForDateReply resultOrders=(MessageGetAllTelephoneOrdersForDateReply)mainMenu.ms.client.GetMessage();
					Vector<Vector> orders=resultOrders.getResult();
					allOrders.removeAllElements();
					for(int i=0 ; i<orders.size();i++)
					{
						allOrders.add(orders.get(i));
					}

					tbl.repaint();
					tbl.validate();
					
					refreshTotalPanel();
					
					mainMenu.getContentPane().validate();
				}
				catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
			}
		});
		return refreshBtn;
	}
	
	
	
	
	
		private JButton getCurrentDateBtn()
		{
			currentDateBtn=new JButton("הזמנות של היום");
			
			currentDateBtn.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {									
				
					DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
					Date date = new Date();
					globalDate=dateFormat.format(date);
					
					String year=globalDate.substring(0, 4);
					String month=globalDate.substring(5, 7);
					String day=globalDate.substring(8,10);
					dateForSearch.getModel().setDate(Integer.parseInt(year), Integer.parseInt(month)-1, Integer.parseInt(day));
					MessageGetAllTelephoneOrdersForDate msgAllOrders=new MessageGetAllTelephoneOrdersForDate(globalDate);
					try {
						mainMenu.ms.client.sendToServer(msgAllOrders);
						MessageGetAllTelephoneOrdersForDateReply resultOrders=(MessageGetAllTelephoneOrdersForDateReply)mainMenu.ms.client.GetMessage();
						Vector<Vector> orders=resultOrders.getResult();
						allOrders.removeAllElements();
						for(int i=0 ; i<orders.size();i++)
						{
							allOrders.add(orders.get(i));
						}
						
						tbl.repaint();
						tbl.validate();
						
						refreshTotalPanel();
						
						mainMenu.getContentPane().validate();
						
					}
					catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} 
					
					
				}
			});	
				
		
		return currentDateBtn;
	}
	
	
	
	
	private JDatePickerImpl getOrderDate()
	{
	 JDatePickerImpl orderDate = (JDatePickerImpl) JDateComponentFactory.createJDatePicker();
	 orderDate.getModel().setSelected(true);
	 return orderDate;
	}
	 
   
	
	
	private Vector <String> inputCheck()
	 {
		 Vector<String> result=new Vector<String>();
		 
		 
//=================================================check for name================================
	      
	     String name=nameTxt.getText();
	     if(name.length()==0) result.add("יש להקיש שם");
	    
	     
	
	     

	 
	     
//============================================check for telephone======================	 
	     
	     String tel = phoneNoTF.getText();
	     if (tel.length() != 0) 
	      {
	    	  if(tel.length()<9 || tel.length()>10) result.add("מספר טלפון לא תקין");
	          for(int i=0; i<tel.length();i++)
	        	  if (tel.charAt(i)<'0'|| tel.charAt(i)>'9')
		    		 {
		    			 result.add("מספר טלפון לא תקין.יש להקיש ספרות בלבד");
		    			 break;
		    		 }	    
		      }
	      else 
	      {
	    	  result.add("יש להקיש מספר טלפון ");	
	      }
	     
//============================================check for no of persons=======================	 	     
	     
	     String num = noOfPersonsTF.getText();
	     if (num.length() != 0) 
	      {
	    	  
	          for(int i=0; i<num.length();i++)
	        	  if (tel.charAt(i)<'0'|| tel.charAt(i)>'9')
		    		 {
		    			 result.add("מספר הסועדים לא תקין.יש להקיש ספרות בלבד");
		    			 break;
		    		 }	    
		      }
	      else 
	      {
	    	  result.add("יש להקיש את מספר הסועדים ");	
	      }
	     

	     
		 return result;
		 
	 }
	
	
	public void addInsertOrderPanel()
	{
		if(insertOrderPanel!=null) this.remove(insertOrderPanel);
		if(changeOrderPanel!=null) this.remove(changeOrderPanel);
		this.add(getInsertOrderPanel(),BorderLayout.EAST);
		mainMenu.getContentPane().validate();
	}
	
	
	
	
	public void addChangeOrderPanel()
	{
		if(insertOrderPanel!=null) this.remove(insertOrderPanel);
		if(changeOrderPanel!=null) this.remove(changeOrderPanel);
		this.add(getChangeOrderPanel(),BorderLayout.EAST);
		mainMenu.getContentPane().validate();
	}
	
	
	
	

	@Override
	public void tableChanged(TableModelEvent avg) {
		int row = avg.getFirstRow();
        int column = avg.getColumn();
        String type=null;
        DefaultTableModel model = (DefaultTableModel)avg.getSource();
        String columnName = model.getColumnName(column);
        
        
       
        String value =(String) model.getValueAt(row, column);
        if (column==5) type="status";
        if (column==6) type="restTable";
        
        String orderId=(String) model.getValueAt(row, 7);
        MessageUpdateTableOfTelephoneOrder	msgUpd=new MessageUpdateTableOfTelephoneOrder(value,type,orderId);
        try {
			mainMenu.ms.client.sendToServer(msgUpd);
			
		}catch (IOException e1) {
			// TODO Auto-generated catch block
			
			e1.printStackTrace();
		}
	}
	

	
	
	
	public Vector<String> getSelectedRowVec() {
		return selectedRowVec;
	}

	public void setSelectedRowVec(Vector<String> selectedRowVec) {
		this.selectedRowVec = selectedRowVec;
	}

	
	/*
	@Override
	public void tableChanged(TableModelEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	*/
	
	
private void refreshTotalPanel()
{
	totalPanel.removeAll();
	
	JLabel totalNumberOfPersonsTxt=new JLabel ("          סה''כ מספר האנשים : ");
	JLabel numberOfNotCameTxt =new JLabel ("          מספר האנשים שתרם הגיעו : ");
	JLabel totalNumberOfOrdersTxt=new JLabel("          סה''כ הזמנות : ");
	JLabel numberOfOpenOrdersTxt=new JLabel("          מספר ההזמנות הפתוחות : ");
	
	int totalPersonsInt=0;
	int numberOfNotCame=0;
	int numberOfOpenOrders=0;
	for(int i=0;i<allOrders.size();i++)
	{
		String noOfPer=(String) allOrders.get(i).get(2);
		String status=(String) allOrders.get(i).get(5);
		
		if(status.equals("פתוח"))
		{
			numberOfNotCame=numberOfNotCame+Integer.parseInt(noOfPer);
			numberOfOpenOrders++;
		}
		totalPersonsInt=totalPersonsInt+Integer.parseInt(noOfPer);
	}
	
	JLabel noOfOpenOrders=new JLabel(Integer.toString(numberOfOpenOrders));
	totalPanel.add(noOfOpenOrders);	
	totalPanel.add(numberOfOpenOrdersTxt);
	
	JLabel totalNoOfOrders=new JLabel(Integer.toString(allOrders.size()));
	totalPanel.add(totalNoOfOrders);	
	totalPanel.add(totalNumberOfOrdersTxt);
	
	JLabel numOfNotCame=new JLabel(Integer.toString(numberOfNotCame));
	totalPanel.add(numOfNotCame);	
	totalPanel.add(numberOfNotCameTxt);
	
	
	JLabel totalNumberOfPersons=new JLabel(Integer.toString(totalPersonsInt));
	totalPanel.add(totalNumberOfPersons);	
	totalPanel.add(totalNumberOfPersonsTxt);
	
	totalPanel.repaint();
	totalPanel.validate();
	
}
	
	
	
	
	
private class RedLine implements Runnable{
	
	private MessageGetAllTelephoneOrdersForDateReply resultOrders;
	private JPanel panel;
	
	
	public RedLine(JPanel p)
	{
		this.panel=p;
	}
	
	
	
	

	final Runnable getMessage = new Runnable() {
		public void run() 
		{
			MessageGetAllTelephoneOrdersForDate msgAllOrders=new MessageGetAllTelephoneOrdersForDate(globalDate);				
			try {
				mainMenu.ms.client.sendToServer(msgAllOrders);
			    resultOrders=(MessageGetAllTelephoneOrdersForDateReply)mainMenu.ms.client.GetMessage();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println("in catch RedLine 1");
				e.printStackTrace();
				resultOrders=null;
				
			}//catch
			
		}//run()
		};
	
	
	
	
	public void run()
	{
		int j=0;
		while(j==0)
		{
		try {
			if (panel.isVisible()==false)
				return;
			
			
			try {
				SwingUtilities.invokeAndWait(getMessage);
				}
				catch (Exception e) {
				e.printStackTrace();
				System.out.println("in catch FireStatus 2");					
				}
			
			Vector<Vector> orders=resultOrders.getResult();
			allOrders.removeAllElements();
			for(int i=0 ; i<orders.size();i++)
			{
				allOrders.add(orders.get(i));
			}
			
			tbl.repaint();
			tbl.validate();
			
			refreshTotalPanel();
			
			mainMenu.getContentPane().validate();
			System.out.println("PfTeleohone Orders ");		
			Thread.sleep(10000);               //sleep 10 sec
		}
		catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
	
}
	
	
	
	

}
